const { Router } = require("express");
const md5 = require("md5");
const JWT = require("jsonwebtoken");
const User = require("../model/User");

const router = new Router();
/* 
注册
url: /api/auth/register
method: POST
params: username password
*/
router.post("/register", async (req, res) => {
  // 获取post请求的参数
  const { username, password, phone, park, workname, type } = req.body;

  // 判断参数是否为空
  if (!username || !password) {
    res.status(400).json({ message: "缺少参数" });
    return;
  }

  // 查询用户是否存在
  const user = await User.findOne({ username });
  if (user) {
    res.status(400).json({ message: "该用户已存在" });
    return;
  }
  let time = Date.now();
  // 注册用户
  await User.create({
    username,
    password: md5(password),
    telephone: phone,
    time,
    park,
    work: workname,
    type,
  });

  res.status(200).json({ message: "注册成功" });
});

/* 
登录
url: /api/auth/login
method: POST
params: username password
*/
router.post("/login", async (req, res) => {
  // 获取post请求的参数
  const { username, password } = req.body;
  console.log(username, password);
  // 判断参数是否为空
  if (!username || !password) {
    res.status(400).json({ message: "缺少参数" });
    return;
  }

  // 查询用户是否存在，判断密码是否正确
  const user = await User.findOne(
    { username, password: md5(password) },
    { password: false }
  ).lean();
  if (user) {
    // 生成token给客户端
    const token = JWT.sign(user, "hello world", { expiresIn: "1d" });
    // 响应客户端token
    res.status(200).json({ message: "登录成功", token, data: user });
  } else {
    res.status(400).json({ message: "用户名或密码错误" });
  }
});

//查询所有后台用户
router.get("/searchall", async (req, res) => {
  let result = await User.find({}, { password: false });
  console.log(result);
  res.status(200).json({ message: "查询成功", result });
});

/* 
检查用户是否登录了
url: /api/auth/check_login
method: GET
header: authorization
*/
router.use(require("../middleware/auth.js"));

router.get("/check_login", async (req, res) => {
  res.status(200).json({ message: "登录成功", data: req.userInfo });
});

module.exports = router;
